<template>
<div class="choose-fileslist">
    <upload v-if="config.model === 'display'" ref="uploadlist" :config="uploadConfig" :saveChangeEvt="uploadChange" :changeEvt="uploadOutPutChange" :modelChangeEvt="modelChangeEvt"></upload>
    <el-dialog custom-class="wlm-form-dialog dialog-table choose-files" width="60%" :append-to-body="true" :visible.sync="dialogTableVisible" @close="clearData" @open="dialogGetData">
        <div class="wlm-dialog-fixheader">
            <span class="wlm-dialog-inlenr">{{`${chooseFileTitle[$type]}选择器`}}</span>
        </div>
        <!-- <el-scrollbar> -->
            <div class="wlm-table-content">
                <div class="wlm-dialog-main">
                    <div class="flex-row">
                        <el-scrollbar>
                            <div class="goods-menu">
                              <!-- 搜索开始 -->
                              <div style="margin-bottom: 10px;">
                                  <el-input
                                    placeholder="请输入内容"
                                    v-model="group_name">
                                     <el-button slot="append" icon="el-icon-search"  @click="handSearch(group_name)"></el-button>
                                    <!-- <i slot="suffix" class="el-input__icon el-icon-search" @click="handSearch(group_name)"></i> -->
                                  </el-input>
                              </div>
                              <!-- 搜索结束 -->
                                <div class="goods-menu-item" :class="{'is-active':tableFormatData.userTable.files.group_id === item.group_id}" v-for="(item, index) in menuData" :key="index" @click="handleNodeClick(item)">
                                    <i class="el-icon-circle-close   rate" v-if="tableFormatData.userTable.files.group_id === item.group_id && item.group_id && item.group_id != 'all'" @click.stop="delMenu(item.group_id,index)"></i>
                                    <span class="ellipsis" style="width: 124px;line-height: 1;">{{item.group_name}}</span>
                                </div>
                            </div>
                        </el-scrollbar>
                        <div class="goods-list-box" style="width:80%;">
                            <div class="flex-row flex-justify-b" style="margin-bottom:10px;">
                                <el-select placeholder="移动至" v-model="menuGroup_id" size="small" style="width:130px;margin-left: 10px;" @change="moveToGroup">
                                    <el-option v-for="item in menuDataCopy" :key="item.group_id" :label="item.group_name" :value="item.group_id">
                                    </el-option>
                                </el-select>
                                <div class="flex-row flex-justify-c flex-align-c" style="padding-right:20px;">
                                    <span class="orders-gray font-12" style="padding-right:14px;">{{`${chooseFileTip[$type]}`}}</span>
                                    <div class="upload-box">
                                      <upload ref="upload" :config="uploadFileConfig" :saveChangeEvt="uploadChange" :modelFileChangeEvt="modelChangeEvt"></upload>
                                      <el-button style="padding-left:30px;" type="primary" size="small" @click="uploadTrigger">上传{{`${chooseFileTitle[$type]}`}}</el-button>
                                    </div>
                                </div>
                              
                            </div>

                            <el-scrollbar style="width:100%;max-height: 460px;overflow-x:hidden;">
                                <div v-loading="!isTableGetEnd" class="goods-list-group flex-row flex-warp" style="padding-top: 10px;padding-right: 12px;display:flex;">
                                    <div class="goods-list" v-for="(item, index) in tableFormatData.userTable.tableData" :key="index">
                                      <!-- {{item}} -->
                                        <div class="goods-item flex-col flex-align-c" @click="chooseFile(item.file_id, item)">
                                            <i class="el-icon-circle-close   rate" @click.stop="delFile(item.file_id, item)"></i>
                                            <i class="el-icon-zoom-in amplification" @click="imgOpen(item.file_type == 'image' ? item.file_path : '')"></i>
                                            <div class="img-center" style="display: flex;justify-content:center;" v-if="item.file_path" :style="{'background-image':`url(${item.file_type == 'image' ? item.file_path : ''})`}">
                                                 <!-- {{item.file_type == 'url'}}s -->
                                                  <video
                                                  v-if="$type === 'video' && (item.file_type == 'video'?item.file_type == 'video':item.file_type == 'url')"
                                                  class="video pos-col-center"
                                                  :src="item.file_path"
                                                  controls="controls"
                                                />
                                                <div v-if="item.file_type == 'url'" class="pos-col-center">
                                                  <div style="display:flex;width: 120px;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;">
                                                    <div>{{item.originname}}</div>
                                                  </div>
                                                </div>
                                                <audio
                                                  v-if="$type === 'audio' && item.file_type == 'audio'"
                                                  class="audio pos-col-center"
                                                  :src="item.file_path"
                                                  controls="controls"
                                                />
                                                <div class="mask" v-if="currentRow.includes(item.file_id)">
                                                    <i class="el-icon-check center-icon pos-center"></i>
                                                    <p class="triangle"><i class="el-icon-check"></i></p>
                                                </div>
                                            </div>
                                            <span class="ellipsis">{{item.file_name}}</span>
                                            <!-- <el-button :class="{'is-active':currentRow.includes(item.goods_id)}" type="primary" round plain size="mini" style="font-size:12px;" @click="chooseFile(item.goods_id,item)">{{`${currentRow.includes(item.goods_id)?'取消':'选择'}`}}</el-button> -->
                                        </div>
                                    </div>
                                </div>

                        </el-scrollbar>
                            </div>
                    </div>

                </div>
            </div>
        <!-- </el-scrollbar> -->
       <!-- //解析抖音地址，并可以去水印
        -->
        <div v-if="$type === 'video'">
           <div class="orders-gray" style="display:inline-block;margin-left:210px;margin-top:20px;display:flex;">
            <div>
                 视频地址：
            </div>
            <div>
              <el-input v-model="url" style="width:400px;"></el-input>
               <el-checkbox v-model="shuiyin" true-label="1" false-label="0" style="margin-left:25px;">是否去水印</el-checkbox>
              </div>
           </div>
           <div class="orders-gray" style="display:inline-block;margin-left:240px;margin-top:20px;display:flex;">
            <div>
                 备注：
            </div>
            <div>
               <el-input v-model="remark" style="width:400px;"></el-input>
              </div>
             
           </div>
           <el-button type="primary" style="display:inline-block;margin-left:210px;margin-top:20px;display:flex;" @click="topbtn">上传链接</el-button>
            <div class="orders-gray" style="display:inline-block;margin-left:210px;margin-top:20px;display:flex;">注：去水印暂时只支持抖音链接</div>
            
        </div>
        <span class="orders-gray" style="display:inline-block;margin-left:210px;margin-top:20px;">已选择{{currentRow.length}}张</span>
        <el-select
                style="display:inline-block;margin-left:10px;margin-top:20px;width:120px;"
                class="cut-model-option"
                v-model="cutOptionsModel"
                size="mini"
                placeholder="请选择"
                @change="cutOptionChange"
              >
                <el-option
                  v-for="item in cutOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
        <div class="pagination-content flex-row flex-justify-b" style="margin-top:20px;flex-wrap: wrap;">
            <el-row class="pagination-btns" style="margin-left:200px;margin-bottom: 20px;position: relative">
                <el-popover
                  width="200"
                  v-model="createDialog">
                  <div class="flex-col">
                  <el-input size="small" v-model.trim="groupName" placeholder="请输入分组名称" style="margin-bottom:15px;"></el-input>
                    <div class="flex-row flex-justify-e">
                      <el-button type="primary" size="small" @click="createGroup(groupName)">确定</el-button>
                      <el-button size="small" @click="createDialog = false">取消</el-button>
                    </div>
                  </div>
                  <el-button slot="reference" size="small" style="position: absolute;left: -160px;"><i class="el-icon-circle-plus-outline"></i> 新建分组</el-button>
                </el-popover>
                <el-button size="small" style="margin-left:8px;" @click="deleteAll">取消选择</el-button>
            </el-row>
            <el-pagination style="margin-top:0;margin-bottom:20px;margin-right: 25px;margin-left: 15px;" :disabled="!hasTableData" @size-change="listPageChange" @current-change="listPageChange" :current-page.sync="tableFormatData.userTable.pagination.page" :page-sizes="tableFormatData.userTable.pagination.pagesizes" :page-size.sync="tableFormatData.userTable.pagination.list_rows" layout="total, sizes, prev, pager, next, jumper" :total="hasTableData?tableFormatData.userTable.pagination.total : 0">
            </el-pagination>
        </div>
        <div class="wlm-dialog-fixfooter">
            <span slot="footer" class="dialog-footer">
                  <el-button size="small" @click="toggle">取 消</el-button>
                  <el-button size="small" type="primary" @click="saveChoose">确 定</el-button>
              </span>
        </div>
    </el-dialog>
</div>
</template>

<script>
import {
  getFileGroupList,
  delUploadFileInfo,
  delFileGroup,
  getFileSelectorList,
  addFileGroup,
  batchMoveFile,
} from '@/api/resource'
import {uploadFile} from '@/api/upload'
import upload from '@/components/Upload/index'
import mixins from '@/mixins/mixins'
import defaultConfig from './utils/config'
import {
  tooggleArray
} from '@/utils/index'
export default {
  mixins: [defaultConfig.mixins, mixins.getters('Table')],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    }
  },
  components: {
    upload
  },
  watch: {
    'config.uploadConfig': {
      handler(newData, oldData) {
        if (!!newData && Object.keys(newData)['length'] > 0) {
          Object.assign(this.uploadConfig, newData)
          const { isLocal, params } = this.uploadConfig
          if (isLocal) {
            this.uploadFileConfig.isLocal = isLocal
          }

          if (params) {
            this.uploadFileConfig.params = params
          }
        }
      },
      immediate: true,
      deep: false
    },
    'config.initList': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.$nextTick(() => {
            const result = []
            newData.map((item) => {
              result.push(item)
            })

            this.uploadConfig.initList = result
          })
          console.log(this.displayData)
        }
      },
      immediate: true,
      deep: false
    },
    'config.file_type': {
      handler(newData, oldData) {
        if (newData && typeof newData === 'string' && ['image', 'video', 'audio', 'file'].includes(newData)) {
          this.tableFormatData.userTable.files.file_type = newData
          this.uploadConfig.type = [newData]
          this.uploadFileConfig.type = [newData]
        }
      },
      immediate: true,
      deep: false
    }
  },
  data() {
    return {
      cutOptionsModel: 'true',
      shuiyin:'',
      url:'',
      group_name:'',
      uploadConfig: {
        auto: false,
        isMore: true,
        isLocal: false,
        chooseFile: true,
        limit: 10,
        initList: [],
        type: ['image']
      },
      cutOptions: [{
        value: 'false',
        label: '裁剪上传'
      }, {
        value: 'true',
        label: '普通上传'
      }],
      uploadFileConfig: {
        auto: false,
        isMore: true,
        isLocal: false,
        isCropper: false,
        modelFile: true,
        chooseFile: true,
        isShowList: false,
        params: {},
        type: ['image']
      },
      chooseFileTip: {
        'image': '图片（image）: 2M，支持bmp/png/jpeg/jpg/gif格式',
        'video': '视频（video）：10MB，支持MP4格式',
        'audio': '语音（voice）：2M，播放长度不超过60s，mp3/wma/wav/amr格式',
        'file': '大小不要超过10M'
      },
      chooseFileTitle: {
        'image': '图片',
        'video': '视频',
        'audio': '音频',
        'file': '文件'
      },
      createDialog: false,
      groupName: '',
      url:'',
      shuiyin:'',
      remark:'',
      displayData: [],
      menuGroup_id: '',
      menuData: [],
      menuDataCopy: [],
      currentRow: [],
      closable: true,
      dialogTableVisible: false,
      tableFormatData: {
        current: 'userTable',
        userTable: {
          key: 'userTable',
          api: {
            getList: getFileSelectorList,
            noCreate: true
          },
          tableData: [],
          files: {
            file_name: '',
            file_type: '',
            ids: [],
            checkall: '0',
            group_id: 'all'
          },
          pagination: {
            page: 1,
            list_rows: 10,
            pagesizes: [10, 20, 50],
            total: 0
          }
        }
      }
    }
  },
  computed: {
    $type() {
      return this.config.file_type
    },
    isChooseFile() {
      return this.uploadConfig.chooseFile
    },
    isLimitMax() {
      return [...this.uploadConfig.initList, ...this.displayData]['length'] >= this.uploadConfig.limit
    }
  },
  created() {
  },
  methods: {
    imgOpen(data) {
      window.open(data)
    },
    cutOptionChange(e) {
      this.uploadFileConfig.isCropper = e === 'false'
    },
    
    modelChangeEvt({ file_list, bindKey }) {
      // console.log(val, 'modelChangeEvt')
      this.toggle()
    },
    dialogGetData() {
      this.tableFormatData.userTable.api.noCreate = false
      this.getGroupList()
      this.getTableList()
    },
    // 搜索按钮
    handSearch(group_name){
      this.getGroupList(group_name)
    },
    getGroupList(group_name) {
      getFileGroupList({ group_type: this.$type,group_name:group_name}).then((response) => {
        const {
          data: {
            data: msgData = {}
          }
        } = response
        this.menuDataCopy = msgData
        this.menuData = [{
          group_id: 'all',
          group_name: '全部',
          child: []
        }, {
          group_id: 'is_use',
          group_name: '用户上传',
          child: []
        }, ...msgData]
      })
    },
    toggle() {
      this.dialogTableVisible = !this.dialogTableVisible
      this.$emit('toggleEvt', { isShow: this.dialogTableVisible })
    },
    // 上传视频
    uploadTrigger() {
      this.uploadConfig.chooseFile = false
      this.$refs.upload.uploadTrigger()
    },
    topbtn(){
      if(this.currentRow.length != 0){
          //  this.toggle()
          this.output()
       }else{
           uploadFile({url:this.url,shuiyin:this.shuiyin,remark:this.remark}).then(res=>{
           const { data: { code, msg } } = res
            if(code==1){
              this.$message.success('操作成功！')
              // this.toggle()
              this.filesSerch()
            }
         })
       }
    },
    //点击确定
    saveChoose() {
        // console.log("dddddddddddddddddd6++++++++++",this.tableFormatData.userTable.tableData)
        // console.log("dddddddddddddddddd6---------------",this.currentRow.length == 0)
        //如果没有选中，就走uploadFile上传url,如果选中就走老方法
        // if(this.url=='' || this.currentRow.length == 0){
        //   return this.$message.error('请填入视频地址，或者选择视频！')
        // }
      //  if(this.currentRow.length != 0){
      //      this.toggle()
      //     this.output()
      //  }else{
      //      uploadFile({url:this.url,shuiyin:this.shuiyin}).then(res=>{
      //      const { data: { code, msg } } = res
      //       if(code==1){
      //         this.$message.success('操作成功！')
      //         this.toggle()
      //       }
      //    })
      //  }
        this.toggle()
          this.output()
    },
    createGroup(group_name) {
      if (group_name) {
        const group_type = this.tableFormatData.userTable.files.file_type
        addFileGroup({ group_name, group_type }).then(res => {
          const { data: { code, msg } } = res
          if (code === 1) {
            this.$message.success(msg)
            this.getGroupList()
          } else {
            this.$message.error(msg)
          }
          this.createDialog = false
        })
      } else {
        this.$message.error('请输入分组名称!~')
      }
    },
    moveToGroup(group_id, current = []) {
      const currentRow = this.currentRow
      if (currentRow.length > 0 || current.length > 0) {
        batchMoveFile({ group_id, ids: current.length > 0 ? current : currentRow }).then(res => {
          const { data: { msg, code } } = res
          if (code === 1) {
            if ((current.length === 0)) {
              this.$message.success(msg)
              this.currentRow = []
              this.filesSerch()
            }
          } else {
            this.$message.error(msg)
          }
        })
      } else {
        this.$message.error('请选择图片后移动!~')
      }
    },
    handleNodeClick(data) {
      this.tableFormatData.userTable.files.is_user = data.is_user
      this.tableFormatData.userTable.files.group_id = data.group_id
      this.filesSerch()
    },
    deleteAll() {
      this.currentRow = []
    },
    chooseFile(ids, item) {
      // 单选判断
      console.log("sdoooooooooooooooooo",ids,item)
      this.currentRow = tooggleArray(this.currentRow, ids, this.config.isUnique)
      console.log(this.currentRow)
      if (this.currentRow.includes(ids)) {
        this.displayData.push(item)
      } else {
        const newIndex = this.displayData.findIndex((displayItem) => {
          return displayItem.file_id === ids
        })
        if (newIndex !== -1) {
          this.displayData.splice(newIndex, 1)
        }
      }
      // if( this.currentRow.length ==0 && this.url!=''){
      //   this.displayData.push(this.url)
      //   console.log("yyyyyyyyyyyyyyyyyyy", this.displayData)
      // }
    },
    delMenu(group_id, index) {
      if (group_id) {
        let ids = []
        if (group_id === 'all') {
          this.menuData.map(item => {
            ids.push(item.group_id)
          })
        } else {
          ids = [group_id]
        }

        delFileGroup({ ids }).then(res => {
          const { data: { msg, code } } = res
          if (code === 1) {
            this.menuData.splice(index, 1)
            this.menuDataCopy.splice(index, 1)
            this.tableFormatData.userTable.files.group_id = 'all'
            this.filesSerch()
          } else {
            this.$message.error(msg)
          }
        })
      }
    },
    delFile(cueeent_id, item) {
      const ids = [...this.currentRow, cueeent_id]
      if (ids.length > 0) {
        delUploadFileInfo({ ids }).then(res => {
          const { data: { msg, code } } = res
          if (code === 1) {
            this.$message.success(msg)
            this.filesSerch()
          } else {
            this.$message.error(msg)
          }
        })
        this.currentRow = []
      }
    },
    clearData() {
      this.currentRow = []
      this.displayData = []
      this.uploadConfig.chooseFile = true
      this.$emit('toggleEvt', { isShow: this.dialogTableVisible })
    },
    output() {
      if (Object.prototype.toString.call(this.changeEvt) === '[object Function]') {
        if (this.isChooseFile) {
          const countList = this.config.model === 'display' ? this.$refs.uploadlist.fileList : this.uploadConfig.initList
          const newList = [...countList, ...this.displayData]
          // console.log(this.displayData)
          // const newList = [...this.uploadConfig.initList]
          this.displayData.map(displayItem => {
            const index = newList.findIndex(findItem => {
              return findItem.file_id === displayItem.file_id
            })

            if (index === -1) {
              newList.push(displayItem)
            }
          })
          const limit = this.uploadConfig.limit
          if (this.isLimitMax) {
            if (limit === 1) {
              // JSON.parse(JSON.stringify(this.displayData))
              this.uploadConfig.initList = [newList[newList.length - 1]]
              this.uploadConfig.model === 'display' && (this.displayData = [newList[newList.length - 1]])
            } else {
              newList.splice(limit, newList.length - limit)
              this.uploadConfig.initList = newList
              this.uploadConfig.model === 'display' && (this.displayData = newList)
            }
          } else {
            this.uploadConfig.initList = newList
            this.uploadConfig.model === 'display' && (this.displayData = newList)
          }
          console.log(this.displayData, 'this.displayData++++++++++++++')

        }
       console.log("复合大师开发的",this.changeEvt)
       this.changeEvt({ currentRow: this.currentRow, displayData: this.displayData, key: 'ChooseFiles', type: [this.$type], isLimitMax: this.isLimitMax }, this.updateConfig.bindKey)
      }
      this.clearData()
    },
    uploadChange(params) {
      console.log("iiiiiiiiiiiiiiiiiiiii",params)
      const group_id = this.tableFormatData.userTable.files.group_id
      if (group_id !== '') {
        const result = []
        params.map(item => { result.push(item.file_id) })
        this.moveToGroup(group_id, result)
      }
      const newList = [...this.tableFormatData.userTable.tableData]
      params.map(displayItem => {
        const index = newList.findIndex(findItem => {
          return findItem.file_id === displayItem.file_id
        })

        if (index === -1) {
          this.tableFormatData.userTable.tableData.unshift(displayItem)
        }
      })
    },
    uploadOutPutChange(params) {
      if (
        Object.prototype.toString.call(this.changeEvt) === '[object Function]' &&
        this.updateConfig.bindKey
      ) {
        this.changeEvt(params, this.updateConfig.bindKey)
        // this.changeEvt({ currentRow: this.currentRow, displayData: this.displayData, key: 'ChooseFiles', type: [this.$type], isLimitMax: this.isLimitMax }, this.updateConfig.bindKey)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .pagination-content .el-input__suffix{
  display: none;
}
</style>
